<?php
namespace admin\action;

use herosphp\core\Loader;
use herosphp\http\HttpRequest;
use herosphp\utils\AjaxResult;
use herosphp\bean\Beans;
use herosphp\core\WebApplication;
use api\utils\PayApiClient;
use herosphp\core\Log;

/**--tmpl-use--**/

use common\action\CommonAction as BaseAction;


class CommonAction extends BaseAction {
    //消息类型常量 info warning success danger
    const MESSAGE_ERROR = 'danger'; //严重错误
    const MESSAGE_WARN = 'warning'; //警告
    const MESSAGE_INFO = 'info'; //普通提示
    const MESSAGE_SUCESS = 'success'; //操作成功

    const COM_ERR_MSG = '(⊙o⊙) 系统出了小差.'; //通用报错类型
    const NO_RECORDS = '(⊙o⊙) 找不到对应的记录.'; //找不到记录
    const NO_PERMISSION = 'O(∩_∩)O 对不起，你没有操作权限， 请联系管理员添加权限.'; //没有权限

    public function C_start()
    {
        parent::C_start();
        $rbacService = Beans::get("admin.adminManager.service");
        $request = WebApplication::getInstance()->getHttpRequest();

        $configs = WebApplication::getInstance()->getConfigs();
        $this->setTemplate($configs['admin_template']);

        //登录页放行
        if($request->getModule() == 'admin' && ($request->getAction() == 'login')){
            return ;
        }
        if(!$rbacService->isLogin())
        {
            header('location:'.url('/admin/login/index?uri='.urlencode($_SERVER['REQUEST_URI'])));
            exit(0);
        }
        $myInfo = $rbacService->getLoginManager();
        $skin = $this->getSkin();
        $this->assign('skin', $skin);
        $field_arr = $this->getCustomForm();
        $this->assign('custom_field_arr', $field_arr);
        $this->assign('myInfo' , $myInfo);
        $this->assign('priv' ,$myInfo['priv']);
        //后台 index 控制器广告
        if($request->getModule() == 'admin' && ($request->getAction() == 'index')){
            return ;
        }
        if(!$rbacService->hasPermission($request->getModule() . '/' . $request->getAction() . '/' .$request->getMethod()))
        {
            //判断请求的类型,如果是ajax请求则使用ajax返回
            if ( strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) {
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_PERMISSION);
            } else {
                //echo $ss=self::NO_PERMISSION;
                //location('/admin/index/error/?type=danger&message='.base64_encode(self::NO_PERMISSION));
                location('/admin/index/error/?type=danger&message='.self::NO_PERMISSION);

            }
        }

        /**--tmpl-starttodo--**/
    }

    /**
    * 设置某个字段的值,用于接收开关ajax
    * @Author Liuyi
    * @Create 2016-11-1 10:18:50
    * @param HttpRequest $request
    */
    public function set(HttpRequest $request) {
        $field = $request->getParameter('field', 'trim');
        $value = $request->getParameter('value', 'trim');
        $id = $request->getParameter('id', 'trim');

        if ( empty($id) || empty($field) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $service = Beans::get($this->getServiceBean());
        if ( $service->set($field, $value, $id) ) {
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }
    }

    /**
    * 更新数据
    * @Author Liuyi
    * @Create 2016-11-1 11:13:50
    * @param array $data
    * @param $id
    * @param $callback 回调函数
    */
    public function __update(array $data, $id, $callback=null) {

        if ( empty($data) || empty($id) ) AjaxResult::ajaxFailtureResult();

        $data['updatetime'] = date('Y-m-d H:i:s');

        $service = Beans::get($this->getServiceBean());
        if ( $service->update($data, $id) ) {
            if ( !is_null($callback) ) {
                call_user_func($callback, $service);
            }
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }

    }
    /* 记录日志
    * @param $remark : 日志说明 ，注当为false时表示该方法不记录日志
    * @param $name : 操作名称，默认为空，会从权限表查出操作对应的名称
    * 注：默认为所有ajax成功返回的方法都记录日志。
    * 若remark 没有给会值 ，默认remark 会从request中提取信息
    */
    protected function log($remark = '',$name = ''){

        $this->assign('__log_remark',$remark);
        $this->assign('__log_name',$name);
    }
    private function __log()
    {
        $remark = $this->getTemplateVar('__log_remark');
        $opname = $this->getTemplateVar('__log_name');

        if($remark === false){
            return ;
        }
        $app = WebApplication::getInstance();
        $request = $app->getHttpRequest();
        $module = $request->getModule();
        $action = $request->getAction();
        $method = $request->getMethod();
        $key = strtolower($module . '/' . $action . '/' . $method);
        $keyOpt = str_replace(array('do_','deletes'),array('','delete'),$key);
        $rbacService = Beans::get('admin.adminManager.service');
        $nodes = $rbacService->getNodeArray();
        if(!$opname)
        {
            foreach($nodes as $v)
            {
                if($v['node_key'] == $keyOpt)
                {
                    $opname = $v['name'];
                }
            }
        }
        if(!$remark)
        {
            $id = $request->getParameter('id');
            $ids = $request->getParameter('ids');
            $data = $request->getParameter('data');
            $name ='';$title = '';
            foreach($data as $k => $v)
            {
                if(strpos($k,'name') !== false)
                {
                    $name = $v;
                }
                if(strpos($k,'title') !== false)
                {
                    $title = $v;
                }
            }
            switch($method)
            {
                case 'do_add':
                    break;
                case 'do_edit':
                    $remark = "id:{$id}";
                    break;
                case 'delete':
                    $remark = "id:{$id}";
                    break;
                case 'deletes':
                    $remark = "id:".implode(',',$ids);
                    break;
                default:
                    break;
            }
            if($title){
                $remark .= ",标题:".$title;
            }
            if($name){
                $remark .= ",名称:".$name;
            }
            $remark = trim($remark,',');
        }

        $operatorLogService = Beans::get('admin.operationLog.service');
        $data = array(
            'opname' => $opname ? $opname : '',
            'opkey' => str_replace('admin/','',$key),
            'remark' => $remark,
        );
        $operatorLogService->add($data);
    }
    public function __destruct()
    {
        if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
        {
            $content = ob_get_contents();
            $js = json_decode($content,true);
            if($js && is_array($js) && $js['code'] == '000')
            {
                $this->__log();
            }
        }

    }


    /**
     * 删除数据，对于分类下可能有数据，而不给删除
     * @param HttpRequest $request
     * @param $caseService
     */
    public function deleteCate( HttpRequest $request,$caseService) {

        $id = $request->getParameter('id');
        if ( $id == "" ) AjaxResult::ajaxResult('error', COM_ERR_MSG);
        $notice = Beans::get($caseService)->getItems(array('cate_id'=>$id));
        if($notice)	{
            AjaxResult::ajaxResult('001','不能删除，该类型下已有公告',array());
            exit();
        }

        $service = Beans::get($this->getServiceBean());
        $child = $service->getItem(array('parent_id'=>$id));
        if($child)
        {
            AjaxResult::ajaxResult('001','不能删除，该类型有子分类',array());
            exit();
        }
        if ( $service->delete($id) ) {
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }
    }

    /**
     * 删除数据，对于分类下可能有数据，而不给删除
     * @param HttpRequest $request
     * @param * @param $caseService
     */
    public function deletesCate( HttpRequest $request ,$caseService) {

        $ids = $request->getParameter('ids');
        if ( empty($ids) ) AjaxResult::ajaxResult('error', COM_ERR_MSG);

        $notice = Beans::get($caseService)->getItems(array('cate_id'=>array('$in'=>$ids)));
        if($notice)	{
            AjaxResult::ajaxResult('001','不能删除，类型下还有内容',array());
            exit();
        }
        $service = Beans::get($this->getServiceBean());
        $childs = $service->getItems(array("parent_id"=>array('$in'=>$ids)));
        if($childs)
        {
            AjaxResult::ajaxResult('001','不能删除，此类型下还有子类',array());
            exit();
        }
        if ( $service->deletes(array('id' => array('$in' => $ids) ))) {
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }
    }


    /**
     * 获取运营商user数据
     * @param string $field
     * @return bool
     */
    public function __getUserInfo($field='id'){
        //获取运营商大塑支付id
        $api_data['appid'] = appId();
        $api_data['fields'] = $field;
        $url = "api/user/getUserByAppId";

        $result = PayApiClient::send($url, $api_data);
        if ($result->isSucess()){
            $res = $result->getItem();
            if($field != '*' && strpos($field,',') === false){
                return $res[$field];
            }
            return $res;
        }else{
            Log::info($result->getMessage());
            return false;//没有获取到运营商支付id
        }
    }


    /**
     * 获取运营商company数据
     * @param string $field
     * @return bool
     */
    public function __getCompanyInfo($field='company'){
        //获取运营商大塑支付id
        $api_data['appid'] = appId();
        $api_data['fields'] = $field;
        $url = "api/user/getCompanyByAppId";

        $result = PayApiClient::send($url, $api_data);
        if ($result->isSucess()){
            $res = $result->getItem();
            if($field != '*' && strpos($field,',') === false){
                return $res[$field];
            }
            return $res;
        }else{
            Log::info($result->getMessage());
            return false;//没有获取到运营商支付id
        }
    }

    /**
     * 设置mpe后台皮肤
     * @param HttpRequest $request
     */
    function setSkin(HttpRequest $request){
        $skin = $request->getParameter('skin');
        $service = Beans::get("admin.adminSetting.service");
        setCookie('skin',$skin,time()+3600*365,'/');
        $service->setConfigs(array('skin'=>$skin));
        $this->assign('skin', $skin);

        AjaxResult::ajaxSuccessResult();
    }

    /**
     * 获取mpe后台皮肤
     * @return string
     */
    function getSkin(){
        $service = Beans::get("admin.adminSetting.service");
        $skin = $_COOKIE['skin'];
        if($skin){
            return $skin;
        }else{
            $skin = $service->getSetting('skin');
            setCookie('skin',$skin,time()+3600*24*365,'/');
            return $skin?$skin:'blue';
        }
    }


    function setCustomForm(HttpRequest $request){
        $url = $request->getParameter('url');
        $field_arr = $request->getParameter('field_arr');
        $model = Loader::model('customForm');
        $data = array(
            'url'=>$url,
            'field_arr'=>json_encode($field_arr),
        );
        if($model->getItem(array('url'=>$url))){
            $res = $model->updates($data,array('url'=>$url));
        }else{
            $res = $model->add($data);

        }
        if($res){
            AjaxResult::ajaxSuccessResult();
        }else{
            AjaxResult::ajaxFailtureResult();
        }
    }

    function getCustomForm(){
        $url = $this->getTemplateVar('module') . '/' . $this->getTemplateVar('action') . '/' . $this->getTemplateVar('method');
        $model = Loader::model('customForm');
        $res = $model->getItem(array('url'=>$url));
        //var_dump(json_decode($res['field_arr']));
        return json_decode($res['field_arr']);
    }
}
